<!DOCTYPE>
<html>
  <head>
    <title>聊天室</title>
    <script src="./js/jquery-1.12.3.min.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="./css/chatroom.css"/>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <link rel="icon" type="image/png" href="/Image/logo.png">
<style>
body{
	margin-top:5px;
}
#notice-bar {
  position: sticky;
  top: 0;
  z-index: 999;
  border-bottom: 1px solid #ffe58f;
  font-size: 16px;
  letter-spacing: 1px;
}
#close-notice:hover {
  color: #d48806;
}
</style>
</head>
  <body>
    <div id="notice-bar" style="display:none; background: #fffbe6; color: #d48806; padding: 8px 16px; font-weight: bold;">
      <marquee id="notice-content"></marquee>
      <span id="close-notice" style="float:right;cursor:pointer;color:#faad14;font-size:18px;margin-left:10px;">×</span>
    </div>
    <div class="container">
    	<div class="row">
    		<div class="col-md-3">
    		<div class="panel panel-primary">
				  <div class="panel-heading">
				    <h3 class="panel-title">当前登录用户</h3>
				  </div>
				  <div class="panel-body">
				    <div class="list-group">
					 <a href="#" class="list-group-item">你好，<span id="user"></span></a>
					 <a href="logout" class="list-group-item">退出</a>
					</div>
				  </div>
				</div>
    			<div class="panel panel-primary" id="online">
				  <div class="panel-heading">
				    <h3 class="panel-title">当前在线的其他用户</h3>
				  </div>
				  <div class="panel-body">
				    <div class="list-group" id="users">
					</div>
				  </div>
				</div>
				<div class="panel panel-primary">
				  <div class="panel-heading">
				    <h3 class="panel-title">群发系统广播</h3>
				  </div>
				  <div class="panel-body">
				    <input type="text" class="form-control"  id="msg" /><br>
				    <button id="broadcast" type="button" class="btn btn-primary">发送</button>
				  </div>
				</div>
    		</div>
  			<div class="col-md-9">
  				<div class="panel panel-primary">
				  <div class="panel-heading">
				    <h3 class="panel-title" id="talktitle"></h3>
				  </div>
				  <div class="panel-body">
				    <div class="well" id="log-container" style="height:400px;overflow-y:scroll">
				    
				    </div>
				    	<input type="text" id="myinfo" class="form-control col-md-12" /> <br>
				    	<button id="send" type="button" class="btn btn-primary">发送</button>
				    </div>
				</div>
  			</div>
    	</div>
    </div> 
<!-- 页脚声明和操作手册 -->
<footer style="width:100%;text-align:center;margin-top:30px;color:#888;font-size:14px;">
  <h3 style="font-weight: bold ;color: black ">本系统最终解释权归祥睿夫子所有</h3>
	<br>
	<br>
  <h4 style="font-weight: bold; color:black;">联系方式：+86 134 7427 7036</h4>
</footer>
<!-- 悬浮操作手册按钮 -->
<button id="manualBtn" class="btn btn-info shadow" style="position:fixed;right:32px;bottom:32px;z-index:1000;border-radius:50px;padding:12px 28px;font-size:16px;">操作手册</button>
<script>
Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}
    $(document).ready(function() {
    	var user;
    	var uid;
    	// 指定websocket路径
	    var websocket;
    	$.get("/currentuser",function(data){
    		user = data.name;
    		uid = data.uid;
    		$("#user").html(user);

	        if ('WebSocket' in window) {
				websocket = new WebSocket("ws://192.168.1.14:8082/webSocket/"+user);
			}
			websocket.onmessage = function(event) {
	       	 var data=JSON.parse(event.data);
	            if(data.to==0){//上线消息
	            	if(data.text!=user)
	            	{	
	            		$("#users").append('<a href="#" onclick="talk(this)" class="list-group-item animate-fade-in-up">'+data.text+'</a>');
	            		alert(data.text + "上线了");
	            	}
	            }else if(data.to==-2){//下线消息
	            	if(data.text!=user)
	            	{	
	            		$("#users > a").remove(":contains('"+data.text+"')");
	            		alert(data.text + "下线了");
	            	}
	            }else if(data.type === "notice") {
	                showNoticeBar("系统消息：" + data.text);
	                return;
	            }else if(data.type === "broadcast") {
	                // 群发消息显示
	                var displayName = "群发消息"
	                $("#log-container").append(
	                    "<div class='message-row system'><div class='bubble-broadcast animate-pop-in'><i class='fa fa-bullhorn me-2'></i><span class='fw-bold'>" + displayName + "</span> <span style='font-size:13px;color:#bfa500'>" + (data.date || "") + "</span><br>" + data.text + "</div></div>"
	                );
	                scrollToBottom();
	                return;
	            }else if(data.type === "system" || data.from=="系统消息") {
	                var sysTime = data.date ? data.date : new Date().format("yyyy-MM-dd hh:mm:ss");
	                $("#log-container").append("<div class='message-row system'><div class='bubble-system animate-pop-in'><i class='fa fa-bell me-2'></i><span class='fw-bold'>系统消息</span> <span style='font-size:13px;color:#bfa500'>"+sysTime+"</span><br>"+data.text+"</div></div>");
	                scrollToBottom();
	                return;
	            }else if(data.from && data.from===user){
	            	// 自己发的消息
	            	$("#log-container").append("<div class='message-row self'><div class='bubble-self animate-fade-in-up'><label class='message-time'>我 "+data.date+"</label><div>"+data.text+"</div></div></div>");
	            	scrollToBottom();
	            }else{
	            	// 其他人发的消息
	            	$("#log-container").append("<div class='message-row other'><div class='bubble-other animate-fade-in-up'><label class='message-time'>"+data.from+" "+data.date+"</label><div>"+data.text+"</div></div></div>");
	            	scrollToBottom();
	            }
	            if(data.type === "force_logout") {
	                alert(data.msg || "您的账号已被管理员注销，如有问题请联系管理员");
	                window.location.href = "/login";
	                return;
	            }
	        };
	        
	        $.post("/onlineusers?currentuser="+user,function(data){
    		for(var i=0;i<data.length;i++)
    			$("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">'+data[i]+'</a>');
    		});
    	
    	});
		
        $("#broadcast").click(function(){
        	var data = {};
			data["from"] = user;
			data["to"] = "-1";
			data["text"] = $("#msg").val();
			if (!data["text"]) {
				alert("消息不能为空！");
				return;
			}
			data["date"] = new Date().format("yyyy-MM-dd hh:mm:ss");
			websocket.send(JSON.stringify(data));
			// 不再在这里显示消息，等待WebSocket回传
			$("#msg").val("");
        });
        
        $("#send").click(function() {
        	if ($("body").data("to")==undefined) {
        		alert("请选择聊天对象");
        		return false;
        	}
			var text = $("#myinfo").val();
			if (!text) {
				alert("消息不能为空！");
				return false;
			}
			var data = {};
			data["from"] = user;
			data["to"] = $("body").data("to");
			data["text"] = text;
			data["date"] = new Date().format("yyyy-MM-dd hh:mm:ss");
			websocket.send(JSON.stringify(data));
			// 立即在发送者界面显示消息
			$("#log-container").append("<div class='message-row self'><div class='bubble-self animate-fade-in-up'><label class='message-time'>我 "+data.date+"</label><div>"+text+"</div></div></div>");
			scrollToBottom();
			$("#myinfo").val("");
		});
        
        // 添加回车发送功能
        $("#myinfo").keypress(function(e) {
            if(e.which == 13) {  // 回车键
                $("#send").click();
            }
        });

        $("#msg").keypress(function(e) {
            if(e.which == 13) {  // 回车键
                $("#broadcast").click();
            }
        });
        
        // 按钮点击动画
        $(".btn-primary").on("mousedown",function(){$(this).addClass("animate-pulse-btn")}).on("mouseup mouseleave",function(){$(this).removeClass("animate-pulse-btn")});
    });
   
   function talk(a){
   	$("#talktitle").text("与"+a.innerHTML+"的聊天");
   	$("body").data("to",a.innerHTML);
   }
   function scrollToBottom(){
		var div = document.getElementById('log-container');
		div.scrollTop = div.scrollHeight;
	}

    // 顶部公告栏滚动，20秒后自动消失
    function showNoticeBar(content){
        $('#notice-content').html('<marquee behavior="scroll" direction="left">' + content + '</marquee>');
        $('#notice-bar').fadeIn();
        setTimeout(function() { $('#notice-bar').fadeOut(); }, 30000); // 20秒后自动消失
    }
    $('#close-notice').click(function(){
        $('#notice-bar').fadeOut();
    });

    // 操作手册弹窗
    $(function(){
      $('#manualBtn').click(function(){
        var manual = `
          <div style='text-align:left;line-height:1.8;'>
            <h5>操作手册</h5>
            <ul>
              <li>1. 登录后可进入聊天室，与在线用户实时交流。</li>
              <li>2. 左侧可查看当前在线用户列表，点击用户名可私聊。</li>
              <li>3. 可在"群发系统广播"输入框发送全员消息。</li>
              <li>4. 管理员可在后台管理用户、强制下线、发布通知等。</li>
              <li>5. 如遇账号问题请联系管理员。</li>
            </ul>
          </div>
        `;
        var modal = $(
          `<div class='modal fade' tabindex='-1' role='dialog'>
            <div class='modal-dialog' role='document'>
              <div class='modal-content'>
                <div class='modal-header'>
                  <h5 class='modal-title'>操作手册</h5>

                </div>
                <div class='modal-body'>${manual}</div>
              </div>
            </div>
          </div>`
        );
        $('body').append(modal);
        modal.modal('show');
        modal.on('hidden.bs.modal', function(){ modal.remove(); });
      });
    });
</script>    
    
  </body>
</html>
